package com.app.conrtoller;

import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.hsy.SendMessage;
import com.app.domain.ldpf.YjSingle;
import com.app.domain.wxgd.WxgdResponseResult;
import com.app.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 东郊质控平台通途
 */
@Slf4j
@RestController
@RequestMapping("/xylc")
public class XylcUploadController {
    @Value("${yj.xylc.serviceHost}")
    private String serviceHost;
    @Value("${yj.xylc.source}")
    private String source;
    @Value("${yj.xylc.token}")
    private String token;
    @Value("${yj.xylc.equNum}")
    private String equNum;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    XylcService uploadService;
    @Autowired
    SendMessageService sendMessageService;
    private static final String SUCCESS_STATE = "1";
    private static final String FAIL_STATE = "0";

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
        try {
            int total = ids.length;
            AtomicInteger succTotal = new AtomicInteger(); // 使用AtomicInteger保证线程安全
            AtomicInteger failTotal = new AtomicInteger();
            StringBuffer responseContent = new StringBuffer();
            responseContent.append("本次共上传数据：【" + total + "】条,");
            for (String id : ids) {
                YjData yjData = yjDataService.findOne(id);
                UploadParameter uploadParameter = uploadParameterService.findOne("40");
                String uuid = sendMessageService.ConditionQuery(id);
                if (StringUtils.isEmpty(uuid)) {
                    YjSingle yjSingle = uploadService.getData(yjData, uploadParameter, uuid, equNum);
                    WxgdResponseResult sqResponseResult = uploadService.sendMessage(serviceHost, yjSingle, source, token);
                    if (sqResponseResult != null && "200".equals(sqResponseResult.getCode())) {
                        //主表上传成功
                        SendMessage sendMessage = new SendMessage();
                        sendMessage.setSbbh(yjData.getDevice_code());
                        sendMessage.setLh(yjData.getBridge_code());
                        sendMessage.setKh(yjData.getDuct_code());
                        sendMessage.setBusi_type("mudjack");
                        sendMessage.setUpload_time(new Date());
                        sendMessage.setUuid(yjSingle.getUuId());
                        sendMessage.setStatus("0");
                        sendMessageService.insert(sendMessage);
                        updateState(SUCCESS_STATE, String.valueOf(yjData.getId()));
                        succTotal.incrementAndGet();
                    } else {
                        updateState(FAIL_STATE, String.valueOf(yjData.getId()));
                        failTotal.incrementAndGet();
                    }
                } else {
                    YjSingle yjSingle = uploadService.getData(yjData, uploadParameter, uuid, equNum);
                    WxgdResponseResult sqResponseResult = uploadService.sendMessage(serviceHost, yjSingle, source, token);
                    if (sqResponseResult != null && "200".equals(sqResponseResult.getCode())) {
                        updateState("1", String.valueOf(yjData.getId()));
                        succTotal.incrementAndGet();
                    } else {
                        updateState("0", String.valueOf(yjData.getId()));
                        failTotal.incrementAndGet();
                    }
                }
            }
            responseContent.append("成功【" + succTotal.get() + "】条,失败" + failTotal.get() + "条");
            externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        } catch (Exception e) {
            // 对于所有捕获的异常，可以记录日志并返回一个通用的错误响应
            System.err.println("上传过程中发生异常：" + e.getMessage());
            log.error("上传过程中发生异常：" + e.getMessage());
            externalResponse = new ExternalResponse(0, "上传过程中发生错误", "");
        }

        return externalResponse;
    }


    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}